import traceback
import docker


class DockerAutomation:
    def __init__(self):
        self.client = docker.from_env()
        self.container = None
        self.docker_id = ""

    def create_run_container(self, image, start_time, end_time, tag="latest"):
        """
        创建并且启动容器
        :return: container
        """
        self.container = self.client.containers.run(
            image=f"{image}",
            detach=True,
            tty=False,
            stdin_open=True,
            auto_remove=False,
            command=f"python main.py --start_time {start_time} --end_time {end_time}",
            # environment=environment,
            # name=docker_name,
            # ports={"80": 80},
            # network = ...,
            # volumes={
            #     "~/containers/aiops-backend": {
            #         "bind": "/deeplog/backend",
            #         "mode": "ro",
            #     }
            # },
        )
        print("success")
        self.docker_id = self.container.id
        return self.container

    def run_command(self, command):
        """
        在容器中执行脚本
        :param command:
        :return: NULL
        """
        try:
            exit_code, output = self.container.exec_run(
                cmd=command, stdout=False, stderr=False
            )
            return exit_code, output
        except Exception as e:
            # self.client.close()
            # print("执行该命令失败" + traceback.format_exc())
            pass

    def remove_docker(self):
        """
        删除容器
        :return: NULL
        """
        try:
            self.container.stop()
            print("stop successfully!")
            self.container.remove()
            print("remove successfully!")
        except Exception as e:
            print(f"删除容器 {self.docker_id} 失败: ")
            # self.client.close()
            pass

    def get_container(self, container_id):
        try:
            # 获取容器对象
            self.container = self.client.containers.get(container_id)
            self.docker_id = container_id
        except Exception as e:
            return None
